package utils


import (
	"time"
	"strconv"
	"fmt"
	"os"

	"bytes"
	"io"
	"io/ioutil"
	"math"
)

const MARKET_SH = "SH"
const MARKET_SZ = "SZ"

func GetMarket(stockcode string) string {
	if stockcode[0:2] == "60" {
		return MARKET_SH
	} else {
		return MARKET_SZ
	}

}

func GetCloseTimeInt(marketType string) int32 {
	if marketType == MARKET_SH {
		return 150000000
	} else {
		return 145700000
	}
}


func MakeDuration(t int32)time.Duration {
	s := strconv.Itoa(int(t))
	ds := ""
	if len(s) == 8 {
		s = "0" + s
	}
	ds = s[0:2] + "h" + s[2:4] + "m" + s[4:6] + "s" + s[6:] + "ms"
	d, err := time.ParseDuration(ds)
	if err != nil {
		fmt.Println(err)
	}
	return d
}

func CopyFile(dstName, srcName string) (written int64, err error) {
	src, err := os.Open(srcName)
	if err != nil {
		return
	}
	defer src.Close()
	dst, err := os.OpenFile(dstName, os.O_WRONLY|os.O_CREATE, 0644)
	if err != nil {
		return
	}
	defer dst.Close()
	return io.Copy(dst, src)
}

func CopyAndReplaceFile(dstName, srcName string, oldstr, newstr string) error {
	src, err := os.Open(srcName)
	if err != nil {
		return err
	}
	dst, err := os.OpenFile(dstName, os.O_RDWR|os.O_CREATE, 0644)
	if err != nil {
		return err
	}
	defer dst.Close()
	io.Copy(dst, src)
	src.Close()

	dst.Seek(0, 0)
	fd, err := ioutil.ReadAll(dst)
	if err != nil {
		return err
	}
	pos := bytes.Index(fd, []byte(oldstr))
	temp := fd[pos : pos+len(newstr)]
	fd = bytes.Replace(fd, temp, []byte(newstr), len(newstr))
	dst.Seek(0, 0)
	dst.Write(fd)
	return nil

}


func OpenTime(now time.Time) time.Time{
	timestamp := now.Unix() - int64(now.Second()) - int64(60 * now.Minute())-int64(3600*now.Hour())+int64(9.5*3600)
	return time.Unix(timestamp, 0)
}

func CloseTimeNoon(now time.Time)time.Time{
	timestamp := now.Unix() - int64(now.Second()) - int64(60 * now.Minute())-int64(3600*now.Hour())+int64(11.5*3600)
	return time.Unix(timestamp,0)
}

func OpenTimeNoon(now time.Time)time.Time{
	timestamp := now.Unix() - int64(now.Second()) - int64(60 * now.Minute())-int64(3600*now.Hour())+int64(13*3600)
	return time.Unix(timestamp,0)
}


func CloseTime(now time.Time)time.Time{
	timestamp := now.Unix() - int64(now.Second()) - int64(60 * now.Minute())-int64(3600*now.Hour())+int64(15*3600)
	return time.Unix(timestamp,0)
}



func IsInTradingTime(t time.Time)bool{
	if (t.Unix()>=OpenTime(t).Unix()&&t.Unix()<=CloseTimeNoon(t).Unix())||(t.Unix()>=OpenTimeNoon(t).Unix()&&t.Unix()<=CloseTime(t).Unix()){
		return  true
	}
	return false
}



func AbsInt32(i int32)int32{
	f:=math.Abs(float64(i))
	return int32(f)
}